<?php
class Services_Ebay_Message extends QDB_ActiveRecord_Abstract
{
	/**
	 * 返回对象的定义
	 *
	 * @static
	 *
	 * @return array
	 */
	static function __define()
	{
		return array
		(
			// 指定该 ActiveRecord 要使用的行为插件
			'behaviors' => '',

			// 指定行为插件的配置
			'behaviors_settings' => array
			(
			    # '插件名' => array('选项' => 设置),
			),

			// 用什么数据表保存对象
			'table_name' => 'services_ebay_message',

			// 指定数据表记录字段与对象属性之间的映射关系
			// 没有在此处指定的属性，QeePHP 会自动设置将属性映射为对象的可读写属性
			'props' => array
			(
				// 主键应该是只读，确保领域对象的“不变量”
				'id' => array('readonly' => true),

				/**
				 *  可以在此添加其他属性的设置
				 */
				# 'other_prop' => array('readonly' => true),

				/**
				 * 添加对象间的关联
				 */
				# 'other' => array('has_one' => 'Class'),

			),

			/**
			 * 允许使用 mass-assignment 方式赋值的属性
			 *
			 * 如果指定了 attr_accessible，则忽略 attr_protected 的设置。
			 */
			'attr_accessible' => '',

			/**
			 * 拒绝使用 mass-assignment 方式赋值的属性
			 */
			'attr_protected' => 'id',

			/**
			 * 指定在数据库中创建对象时，哪些属性的值不允许由外部提供
			 *
			 * 这里指定的属性会在创建记录时被过滤掉，从而让数据库自行填充值。
			 */
			'create_reject' => '',

			/**
			 * 指定更新数据库中的对象时，哪些属性的值不允许由外部提供
			 */
			'update_reject' => '',

			/**
			 * 指定在数据库中创建对象时，哪些属性的值由下面指定的内容进行覆盖
			 *
			 * 如果填充值为 self::AUTOFILL_TIMESTAMP 或 self::AUTOFILL_DATETIME，
			 * 则会根据属性的类型来自动填充当前时间（整数或字符串）。
			 *
			 * 如果填充值为一个数组，则假定为 callback 方法。
			 */
			'create_autofill' => array
			(
				# 属性名 => 填充值
				# 'is_locked' => 0,
			),

			/**
			 * 指定更新数据库中的对象时，哪些属性的值由下面指定的内容进行覆盖
			 *
			 * 填充值的指定规则同 create_autofill
			 */
			'update_autofill' => array
			(
			),

			/**
			 * 在保存对象时，会按照下面指定的验证规则进行验证。验证失败会抛出异常。
			 *
			 * 除了在保存时自动验证，还可以通过对象的 ::meta()->validate() 方法对数组数据进行验证。
			 *
			 * 如果需要添加一个自定义验证，应该写成
			 *
			 * 'title' => array(
			 *	array(array(__CLASS__, 'checkTitle'), '标题不能为空'),
			 * )
			 *
			 * 然后在该类中添加 checkTitle() 方法。函数原型如下：
			 *
			 * static function checkTitle($title)
			 *
			 * 该方法返回 true 表示通过验证。
			 */
			'validations' => array
			(
			),
		);
	}


/* ------------------ 以下是自动生成的代码，不能修改 ------------------ */

	/**
	 * 开启一个查询，查找符合条件的对象或对象集合
	 *
	 * @static
	 *
	 * @return QDB_Select
	 */
	static function find()
	{
		$args = func_get_args();
		return QDB_ActiveRecord_Meta::instance(__CLASS__)->findByArgs($args);
	}

	/**
	 * 返回当前 ActiveRecord 类的元数据对象
	 *
	 * @static
	 *
	 * @return QDB_ActiveRecord_Meta
	 */
	static function meta()
	{
		return QDB_ActiveRecord_Meta::instance(__CLASS__);
	}


/* ------------------ 以上是自动生成的代码，不能修改 ------------------ */
	
	static function getListByGetMyMessage($shop_ids, $start_time, $end_time, $folder_id = 3)
	{
		foreach ($shop_ids as $s)
		{
			$shop_messages = array();
			$token = Shop_API_Ebay::find('shop_id=?', $s)->asArray()->getOne();
			if ($token && $start_time && $end_time)
			{
				$ps = 200;
				$cp = 0;
				$total_entries = 200;
				$header = array(
					'X-EBAY-API-COMPATIBILITY-LEVEL:' . Q::ini('custom_api/X-EBAY-API-COMPATIBILITY-LEVEL'),
					'X-EBAY-API-DEV-NAME:' . Q::ini('custom_api/X-EBAY-API-DEV-NAME'),
					'X-EBAY-API-APP-NAME:' . Q::ini('custom_api/X-EBAY-API-APP-NAME'),
					'X-EBAY-API-CERT-NAME:' . Q::ini('custom_api/X-EBAY-API-CERT-NAME'),
					'X-EBAY-API-SITEID:0',
					'X-EBAY-API-CALL-NAME:GetMyMessages'
				);
				while ($ps <= $total_entries)
				{
					$cp++;
					$total_entries = 0;
					$xml ='<?xml version="1.0" encoding="utf-8"?>';
					$xml .='<GetMyMessagesRequest xmlns="urn:ebay:apis:eBLBaseComponents">';
					$xml .='  <RequesterCredentials>';
					$xml .='    <eBayAuthToken>' . $token['token'] . '</eBayAuthToken>';
					$xml .='  </RequesterCredentials>';
					$xml .='  <Pagination>';
					$xml .='    <EntriesPerPage>' . $ps . '</EntriesPerPage>';
					$xml .='    <PageNumber>' . $cp . '</PageNumber>';
					$xml .='  </Pagination>';
					$xml .='  <StartTime>' . $start_time . '</StartTime>';
					$xml .='  <EndTime>' . $end_time . '</EndTime>';
					$xml .='  <FolderID>' . $folder_id . '</FolderID>';
					$xml .='  <ErrorLanguage>en_US</ErrorLanguage>';
					$xml .='  <DetailLevel>ReturnHeaders</DetailLevel>';
					$xml .='  <OutputSelector>Messages.Message.sender</OutputSelector>';
					$xml .='  <OutputSelector>Messages.Message.RecipientUserID</OutputSelector>';
					$xml .='  <OutputSelector>Messages.Message.Subject</OutputSelector>';
					$xml .='  <OutputSelector>Messages.Message.MessageID</OutputSelector>';
					$xml .='  <OutputSelector>Messages.Message.ExternalMessageID</OutputSelector>';
					$xml .='  <OutputSelector>Messages.Message.Read</OutputSelector>';
					$xml .='  <OutputSelector>Messages.Message.Flagged</OutputSelector>';
					$xml .='  <OutputSelector>Messages.Message.ReceiveDate</OutputSelector>';
					$xml .='  <OutputSelector>Messages.Message.ExpirationDate</OutputSelector>';
					$xml .='  <OutputSelector>Messages.Message.ItemID</OutputSelector>';
					$xml .='  <OutputSelector>Messages.Message.ResponseDetails.ResponseEnabled</OutputSelector>';
					$xml .='  <OutputSelector>Messages.Message.ResponseDetails.ResponseURL</OutputSelector>';
					$xml .='  <OutputSelector>Messages.Message.ResponseDetails.UserResponseDate</OutputSelector>';
					$xml .='  <OutputSelector>Messages.Message.Folder.FolderID</OutputSelector>';
					$xml .='  <OutputSelector>Messages.Message.Replied</OutputSelector>';
					$xml .='  <OutputSelector>Messages.Message.MessageMedia.MediaName</OutputSelector>';
					$xml .='  <OutputSelector>Messages.Message.MessageMedia.MediaURL</OutputSelector>';
					$xml .='  <WarningLevel>High</WarningLevel>';
					$xml .='  </GetMyMessagesRequest>';
					$result = Helper_BSS_API::ebayAPICall(Q::ini('custom_api/ebay_ws_uri'), $header, $xml, 'GetMyMessages', $cp);
					if ($result['ack'] == SUCCESS)
					{
						$response = simplexml_load_string($result['data']);
						if ($response && $response->Ack == 'Success')
						{
							if (isset($response->Messages[0]->Message))
							{
								$total_entries = count($response->Messages[0]->Message);
								$current_page_messages = Helper_BSS_XML::ebayXMLToMessageArray($s, $response);
								$shop_messages = array_merge($shop_messages, $current_page_messages);
							}
						}
					}
					else
					{
						return array('ack' => FAILURE, 'message' => $result['message']);
					}
				}
				$import_result = Services_Ebay_Message::import($shop_messages);
			}
		}
		return array('ack' => SUCCESS, 'message' => '');
	}
	
	static function reviseMyMessage($message, $flag, $type)
	{
		if (! ($message['replied'] == 1 && $type == 'read'))
		{
			$token = Shop_API_Ebay::find('shop_id=?', $message['shop_id'])->asArray()->getOne();
			if ($token && isset($flag) && isset($type))
			{
				$header = array(
					'X-EBAY-API-COMPATIBILITY-LEVEL:' . Q::ini('custom_api/X-EBAY-API-COMPATIBILITY-LEVEL'),
					'X-EBAY-API-DEV-NAME:' . Q::ini('custom_api/X-EBAY-API-DEV-NAME'),
					'X-EBAY-API-APP-NAME:' . Q::ini('custom_api/X-EBAY-API-APP-NAME'),
					'X-EBAY-API-CERT-NAME:' . Q::ini('custom_api/X-EBAY-API-CERT-NAME'),
					'X-EBAY-API-SITEID:0',
					'X-EBAY-API-CALL-NAME:ReviseMyMessages'
				);
				$xml ='<?xml version="1.0" encoding="utf-8"?>';
				$xml .='<ReviseMyMessagesRequest xmlns="urn:ebay:apis:eBLBaseComponents">';
				$xml .='  <RequesterCredentials>';
				$xml .='    <eBayAuthToken>' . $token['token'] . '</eBayAuthToken>';
				$xml .='  </RequesterCredentials>';
				$xml .='  <MessageIDs>';
				$xml .='  <MessageID>' . $message['message_id'] . '</MessageID>';
				$xml .='  </MessageIDs>';
				if ($type == 'read')
				{
					$xml .='  <Read>' . ($flag == '0' ? 'false' : 'true') . '</Read>';
				}
				if ($type == 'flagged')
				{
					$xml .='  <Flagged>' . ($flag == '0' ? 'false' : 'true') . '</Flagged>';
				}
				$xml .='</ReviseMyMessagesRequest>';
				$result = Helper_BSS_API::ebayAPICall(Q::ini('custom_api/ebay_ws_uri'), $header, $xml, 'ReviseMyMessages');
				if ($result['ack'] == SUCCESS)
				{
					$response = simplexml_load_string($result['data']);
					if ($response && $response->Ack == 'Success')
					{
						if ($type == 'read')
						{
							$update = '`read`=' . $flag;
						}
						if ($type == 'flagged')
						{
							$update = '`flagged`=' . $flag;
						}
						QDB::getConn()->execute('update services_ebay_message set '. $update . ' where message_id=\'' . $message['message_id'] . '\'');
						return array('ack' => SUCCESS, 'message' => '');
					}
					else
					{
						return array('ack' => FAILURE, 'message' => isset($response->Errors[0]->ShortMessage[0]) ? (string)$response->Errors[0]->ShortMessage[0] : '');
					}
				}
				else
				{
					return array('ack' => FAILURE, 'message' => $result['message']);
				}
			}
		}
	}
	
	static function getBodyByGetMyMessage($message)
	{
		$token = Shop_API_Ebay::find('shop_id=?', $message['shop_id'])->asArray()->getOne();
		if ($token)
		{
			$header = array(
				'X-EBAY-API-COMPATIBILITY-LEVEL:' . Q::ini('custom_api/X-EBAY-API-COMPATIBILITY-LEVEL'),
				'X-EBAY-API-DEV-NAME:' . Q::ini('custom_api/X-EBAY-API-DEV-NAME'),
				'X-EBAY-API-APP-NAME:' . Q::ini('custom_api/X-EBAY-API-APP-NAME'),
				'X-EBAY-API-CERT-NAME:' . Q::ini('custom_api/X-EBAY-API-CERT-NAME'),
				'X-EBAY-API-SITEID:0',
				'X-EBAY-API-CALL-NAME:GetMyMessages'
			);
			$xml ='<?xml version="1.0" encoding="utf-8"?>';
			$xml .='<GetMyMessagesRequest xmlns="urn:ebay:apis:eBLBaseComponents">';
			$xml .='  <RequesterCredentials>';
			$xml .='    <eBayAuthToken>' . $token['token'] . '</eBayAuthToken>';
			$xml .='  </RequesterCredentials>';
			$xml .='  <DetailLevel EnumType="DetailLevelCodeType">ReturnMessages</DetailLevel>';
			$xml .='  <MessageIDs>';
			$xml .='    <MessageID>' . $message['message_id'] . '</MessageID>';
			$xml .='  </MessageIDs>';
			$xml .='  <ErrorLanguage>en_US</ErrorLanguage>';
			$xml .='  <OutputSelector>Messages.Message.MessageID</OutputSelector>';
			$xml .='  <OutputSelector>Messages.Message.Text</OutputSelector>';
			$xml .='</GetMyMessagesRequest>';
			$result = Helper_BSS_API::ebayAPICall(Q::ini('custom_api/ebay_ws_uri'), $header, $xml, 'GetMyMessages');
			if ($result['ack'] == SUCCESS)
			{
				$response = simplexml_load_string($result['data']);
				if ($response && $response->Ack == 'Success')
				{
					$body = (string)$response->Messages[0]->Message[0]->Text[0];
					$extend = array();
					$extend['body'] = $body;
					Services_Ebay_Message_Extend::update($extend, $message['id']);
					return array('ack' => SUCCESS, 'message' => '', 'text' => (string)$response->Messages[0]->Message[0]->Text[0]);
				}
				else
				{
					return array('ack' => FAILURE, 'message' => isset($response->Errors[0]->ShortMessage[0]) ? (string)$response->Errors[0]->ShortMessage[0] : '');
				}
			}
			else
			{
				return array('ack' => FAILURE, 'message' => $result['message']);
			}
		}
	}
	
	static function import($messages)
	{
		foreach ($messages as $m)
		{
			$message = Services_Ebay_Message::find('message_id=?', $m['message_id'])->getOne();
			if (empty($message['id']))
			{
				$message = new Services_Ebay_Message();
				$message->shop_item_id = $m['shop_item_id'];
				$message->shop_id = $m['shop_id'];
				$message->message_id = $m['message_id'];
				$message->external_message_id = $m['external_message_id'];
				$message->sender = $m['sender'];
				$message->recipient = $m['recipient'];
				$message->flagged = $m['flagged'];
			}
			else
			{
				$message->flagged = $m['flagged'] == 0 ? 0 : ($message['flagged'] == 0 ? 1 : $message['flagged']);
			}
			$message->read = $m['read'];
			$message->receive_time = $m['receive_time'];
			$message->expiration_time = $m['expiration_time'];
			$message->response_enabled = $m['response_enabled'];
			$message->response_time = $m['response_time'];
			$message->folder_id = $m['folder_id'];
			$message->replied = $m['replied'];
			$message->Save();
			$extend = array();
			$extend['response_url'] = $m['response_url'];
			$extend['subject'] = $m['subject'];
			Services_Ebay_Message_Extend::update($extend, $message->id);
			if (isset($m['pictures'][0]['url']))
			{
				Services_Ebay_Picture::create($message->id, Q::ini('custom_flag/services_ebay_picture_type/message_receive/value'), $m['pictures']);
			}
		}
		return array('ack' => SUCCESS, 'message' => '');
	}
	
	static function search($condition, $cp, $ps)
	{
		$columns = array(
			'services_ebay_message.*',
			'shop.name as shop_name'
		);
		$where = Services_Ebay_Message::buildSearchWhere($condition);
		$select = Services_Ebay_Message::find($where)
			->joinLeft('shop', '', 'services_ebay_message.shop_id=shop.id')
			->setColumns($columns)->order('services_ebay_message.receive_time desc');
		if($cp == 0 && ps == 0)
		{
			$pagination = array();
		}
		else
		{
			$select->limitPage($cp, $ps);
			$pagination = $select->getPagination();
		}
		$message = $select->asArray()->getAll();
		return array(
			'ack' => SUCCESS,
			'message' => '',
			'data' => $message,
			'pagination' => $pagination
		);
	}
	
	static function buildSearchWhere($condition)
	{
		$where = '1';
		if ( ! empty($condition['shop_user_mapping']))
		{
			$shop_id = Shop_User_Mapping::getShopIdByUserId();
			$where .= ' and services_ebay_message.shop_id in (\'' . implode('\',\'', $shop_id) . '\')';
		}
		if ( ! empty($condition['begin_receive_time']))
		{
			$where .= ' and services_ebay_message.receive_time>=\'' . $condition['begin_receive_time'] . '\'';
		}
		if ( ! empty($condition['end_receive_time']))
		{
			$where .= ' and services_ebay_message.receive_time<=\'' . $condition['end_receive_time'] . ' 23:59:59\'';
		}
		if (isset($condition['shop_ids']))
		{
			$where .= ' and services_ebay_message.shop_id in (\'' . implode('\',\'', $condition['shop_ids']) . '\')';
		}
		if (isset($condition['read']))
		{
			$read_filter = '0';
			foreach (Q::ini('custom_flag/services_ebay_message_read') as $r)
			{
				if (isset($condition['read'][$r['value']]) && $condition['read'][$r['value']] == $r['value'])
				{
					$read_filter .= ' or services_ebay_message.read=' . $r['value'];
				}
			}
			$where .= ' and (' . $read_filter . ')';
		}
		if (isset($condition['replied']))
		{
			$replied_filter = '0';
			foreach (Q::ini('custom_flag/services_ebay_message_replied') as $r)
			{
				if (isset($condition['replied'][$r['value']]) && $condition['replied'][$r['value']] == $r['value'])
				{
					$replied_filter .= ' or services_ebay_message.replied=' . $r['value'];
				}
			}
			$where .= ' and (' . $replied_filter . ')';
		}
		if (isset($condition['from']))
		{
			$from_filter = '0';
			if (in_array('ebay', $condition['from']))
			{
				$from_filter .= ' or services_ebay_message.external_message_id=\'\'';
			}
			if (in_array('member', $condition['from']))
			{
				$from_filter .= ' or services_ebay_message.external_message_id!=\'\'';
			}
			$where .= ' and (' . $from_filter . ')';
		}
		if ( ! empty($condition['sender']))
		{
			$where .= ' and services_ebay_message.sender=\'' . $condition['sender'] . '\'';
		}
		if (isset($condition['flagged']))
		{
			$flagged_filter = '0';
			foreach (Q::ini('custom_flag/services_ebay_message_flagged') as $f)
			{
				if (isset($condition['flagged'][$f['value']]) && $condition['flagged'][$f['value']] == $f['value'])
				{
					$flagged_filter .= ' or services_ebay_message.flagged=' . $f['value'];
				}
			}
			$where .= ' and (' . $flagged_filter . ')';
		}
		return $where;
	}
}